<template>
  <div class="YBTab" @click="automaticShowItem">
    <div class="YBTab_pre TBTab_btn" v-if="showIcon">
      <el-icon @click="frontTransform"><ArrowLeft /></el-icon>
    </div>
    <div class="YBTab_content" ref="wrapper">
      <div class="list" ref="list">
        <slot></slot>
      </div>
    </div>
    <div class="YBTab_next TBTab_btn" v-if="showIcon">
      <el-icon @click="backTransform"><ArrowRight /></el-icon>
    </div>
  </div>
</template>
<script>export default { name:'CustomTab'}</script>
<script setup>
import { onMounted, ref, computed, onUnmounted } from "vue";
const wrapper = ref(null)
const list = ref(null)
const showIcon = ref(false)
const translateNum = ref(0)
const translateVal = computed(() => '-' + translateNum.value + 'px')
onMounted(() => {
  calcWidth()
  window.addEventListener('resize',() =>  calcWidth())
})
onUnmounted(() => {
  window.removeEventListener('resize',() => calcWidth())
})
const calcWidth = () => {
  const wrapperWidth = wrapper.value.getClientRects()[0].width
  const listWidth = list.value.getClientRects()[0].width
  // console.log(wrapperWidth,listWidth);
  showIcon.value = wrapperWidth < listWidth;
  if(translateNum.value !== 0){
    backTransform()
  }
}
//显示前一页
const frontTransform = () => {
  const wrapperWidth = wrapper.value.getClientRects()[0].width
  const length = translateNum.value - wrapperWidth
  if(length > 0){
    translateNum.value -= wrapperWidth
  }else{
    translateNum.value = 0
  }
}
//显示后一页
const backTransform = () => {
  const wrapperWidth = wrapper.value.getClientRects()[0].width
  const listWidth = list.value.getClientRects()[0].width
  const length = listWidth - (wrapperWidth + translateNum.value)
  if(length > wrapperWidth ){
    translateNum.value += wrapperWidth
  }else{
    translateNum.value += length
  }
}
//边界元素自适应展示在视图区域中
const automaticShowItem = (e) => {
  if(e.target.dataset.type === 'customItem'){
    if(e.target.offsetLeft < translateNum.value){
      translateNum.value -= (translateNum.value - e.target.offsetLeft)
    }else{
      const wrapperWidth = wrapper.value.getClientRects()[0].width
      if((wrapperWidth + translateNum.value) < (e.target.offsetLeft + e.target.offsetWidth)){
        translateNum.value += (e.target.offsetLeft + e.target.offsetWidth - wrapperWidth - translateNum.value)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.YBTab{
  margin:0 auto;
  user-select: none;
  display: flex;
  align-items: center;
  width: 100%;
  &_btn{
    flex: 0 0 20px;
    width: 20px;
    display: flex;
    .el-icon{
      margin:auto;
    }
  }
  &_content{
    flex:1;
    width: 100%;
    overflow: hidden;
    .list{
      width:auto;
      display: flex;
      white-space: nowrap;
      float: left;
      transform: translateX(v-bind('translateVal'));
      transition-duration: 500ms;
    }
  }
}
</style>